package com.mjh.util;

import cn.hutool.core.exceptions.ValidateException;
import cn.hutool.json.JSONException;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTPayload;
import cn.hutool.jwt.JWTUtil;
import cn.hutool.jwt.JWTValidator;
import cn.hutool.jwt.signers.JWTSigner;
import cn.hutool.jwt.signers.JWTSignerUtil;
import lombok.Getter;
import lombok.Setter;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;
import java.rmi.server.UID;
import java.util.Date;
import java.util.Map;

/**
 * @author MJH
 * @date 2021-12-04
 * @Description jwt工具类
 */
@Component
public class JwtUtil {

    //令牌密钥
    private static String KEY;

    //令牌过期时间
    private static int EXPIRESAT;

    @Value("${Jwt.key}")
    public void setKEY(String key){
        KEY=key;
    }

    @Value("${Jwt.expiresAt}")
    public void setEXPIRESAT(int expiresat){
        EXPIRESAT=expiresat;
    }

    /**
     * 令牌验证
     * @param token
     * @return
     */
    public static boolean verificationToken(String token){
        boolean flag =true;
        try {
            JWTValidator.of(token)
                    .validateDate()
                    .validateAlgorithm(JWTSignerUtil.hs256(KEY.getBytes()));

        }catch (ValidateException e){
           flag=false;
           e.printStackTrace();
        }catch (JSONException e){
            //令牌解析异常
            flag=false;

        }


        return flag;
    }


    /**
     * 创建令牌
     * @param payload  令牌载体
     * @return
     */
    public static String createToken(Map<String,Object> payload){


        return JWT.create()
                .setExpiresAt(new Date(System.currentTimeMillis() + (1000 * 60 * 60 * 24 *EXPIRESAT)))
                 .addPayloads(payload)
                .setKey(KEY.getBytes())
                .sign();

    }




    /**
     * 获取令牌载体
     * @param token  令牌
     * @param payload   载体key
     * @return
     */
    public static Object getPayload(String token,String payload){
        JWTPayload pa = JWT.of(token)
                .setKey(KEY.getBytes())
                .getPayload();

        return pa.getClaim(payload);
    }

    /**
     * 从请求头中获取用令牌
     * @param request
     * @param payload
     * @return
     */
    public static Object getPayload(HttpServletRequest request,String payload){
        String token = request.getHeader("token");
        if (token==null) return null;
        return  getPayload(token,payload);

    }
}
